﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//WB Added
using umbraco.interfaces;
using System.Configuration;
using System.Web.Configuration;
using System.Xml;
using umbraco.cms.businesslogic.packager.standardPackageActions;

namespace USTF.Package.PackageActions
{
    public class AddValuesToReservedPath : IPackageAction
    {
        public string Alias()
        {
            return "AddValuesToReservedPath";
        }

        public XmlNode SampleXml()
        {
            //<add key="umbracoReservedPaths" value="/umbraco,/install/,/SUMO/," />

            string sample = "<Action runat=\"install\" undo=\"true/false\" alias=\"AddValuesToReservedPath\" value=\",/myfolder/,/another_folder/,\"></Action>";
            return helper.parseStringToXmlNode(sample);
        }

        public bool Execute(string packageName, XmlNode xmlData)
        {
            string addValue = string.Empty;

            try
            {
                addValue = GetAttributeValueFromNode(xmlData, "value");

                // as long as addValue has a value, update the web.config
                if (addValue != string.Empty)
                {
                    AddValuesToUmbracoReservedPaths(addValue);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
        
        public bool Undo(string packageName, XmlNode xmlData)
        {
            string removeValue = string.Empty;

            try
            {
                removeValue = GetAttributeValueFromNode(xmlData, "value");

                // as long as removeValue has a value, remove it from the web.config
                if (removeValue != string.Empty)
                {
                    RemoveValuesToUmbracoReservedPaths(removeValue);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }


        private void AddValuesToUmbracoReservedPaths(string addValue)
        {
            //Open the web.config file
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");

            //Get the current appSetting "umbracoReservedPaths"
            KeyValueConfigurationElement appSetting = webConfig.AppSettings.Settings["umbracoReservedPaths"];


            //Get current value in umbracoReservedPaths
            string currentValue = appSetting.Value.ToString();

            //Check if the current value ends with a comma, if so remove it
            if(currentValue.EndsWith(","))
            {
                int desiredLength = currentValue.LastIndexOf(",");

                if(desiredLength >= 0)
                {
                    currentValue.Substring(0, desiredLength);
                }
            }

            //Check if the new addValue does not start with a comma
            if(! addValue.StartsWith(","))
            {
                //Current value does not start with comma, add it
                addValue = "," + addValue;
            }

            //Set the new value in the web.config
            appSetting.Value = currentValue + addValue;

            //Save the changes
            webConfig.Save(ConfigurationSaveMode.Modified);
        }

        private void RemoveValuesToUmbracoReservedPaths(string removeValue)
        {
            //Open the web.config file
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");

            //Get the current appSetting "umbracoReservedPaths"
            KeyValueConfigurationElement appSetting = webConfig.AppSettings.Settings["umbracoReservedPaths"];

            //Get current value in umbracoReservedPaths
            string currentValue = appSetting.Value.ToString();

            //Replace the values we added with nothing
            currentValue = currentValue.Replace(removeValue, "");


            //Set the new value in the web.config
            appSetting.Value = currentValue;

            //Save the changes
            webConfig.Save(ConfigurationSaveMode.Modified);
        }

        public static string GetAttributeValueFromNode(XmlNode node, string attributeName)
        {
            string result = string.Empty;

            if (node.Attributes[attributeName] != null)
            {
                //Attribute has an value return that.
                result = node.Attributes[attributeName].InnerText;
            }
            return result;
        }


    }
}